<!-- 搜索栏 -->
<template>
    <div class="search-box">
        <div class="search-params">
            <div class="search-it" v-for="(item, index) in props.searchList" :key="index">
                <!-- input 输入框-->
                <div v-if="item.searchtype == 'input'">
                    <el-input v-model="searchBox[item.key]" :placeholder="item.label" prefix-icon="Search" clearable
                        size="default" @clear="conditionalQuery"
                        :style="{ 'width': item.width ? item.width + 'px' : '' }" />
                </div>
                <!-- time 日期 -->
                <div v-if="item.searchtype == 'time'">
                    <el-date-picker v-model="searchBox[item.key]" type="date" clearable :placeholder="item.label"
                        @clear="conditionalQuery" :style="{ 'width': item.width ? item.width + 'px' : '' }" />
                </div>
                <!--  timeQuantum  时间段选择 -->
                <div v-if="item.searchtype == 'timeQuantum'">
                    <el-date-picker v-model="searchBox[item.key]" type="datetimerange" size="default"
                        :style="{ 'width': item.width ? item.width + 'px' : '' }" range-separator="至" clearable
                        @clear="conditionalQuery" :start-placeholder="item.labelStart ? item.labelStart : '开始时间'"
                        :end-placeholder="item.labelEnd ? item.labelEnd : '结束时间'" />
                </div>
                <!-- select 下拉框 -->
                <div v-if="item.searchtype == 'select'">
                    <el-select v-model="searchBox[item.key]" :placeholder="item.label"
                        :style="{ 'width': item.width ? item.width + 'px' : '200px' }" size="default" clearable
                        @clear="conditionalQuery">
                        <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value" />
                    </el-select>
                </div>
                <!-- Cascader 级联选择器 -->
                <div v-if="item.searchtype == 'cascader'">
                    <el-cascader :options="item.options" :show-all-levels="false" v-model="searchBox[item.key]"
                        @clear="conditionalQuery" size="default" clearable :placeholder="item.label"
                        :style="{ 'width': item.width ? item.width + 'px' : '' }" />
                </div>
            </div>
        </div>

        <!-- 确定按钮  -->
        <div class="submit">
            <el-button type="primary" icon="Search" @click="conditionalQuery" size="default">查询</el-button>
            <!-- 可选的配置项 -->
            <div v-show="props.userPreferences">
                <el-popover :visible="visible" placement="bottom" :width="160">
                    <div v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
                        <el-checkbox v-model="checked" @change="changechecked">全选</el-checkbox>
                        <div style="width: 156px;height: 1px;background: #D3DCE6;margin-top: 6px;"></div>
                        <div class="eltree">
                            <el-tree size='mini' ref="tree" node-key="prop" draggable :data="configList" show-checkbox
                                :props="defaultProps" :allow-drop="allowDrop" @node-drop="sort" @check="check"
                                @check-change="checkChange">
                            </el-tree>
                        </div>
                        <div style="width: 156px;height: 1px;background: #D3DCE6;margin-top: 6px;"></div>
                        <div style="display: flex;font-size: 12px;margin-top: 6px;">
                            <div style="cursor: pointer;color: #8492A6;" @click="resetsetting">重置</div>
                            <div style="cursor: pointer;color: #20A0FF;margin-left: 20px;" @click="savesetting">保存</div>
                        </div>
                    </div>
                    <template #reference>
                        <div class="btn-config" @click="visible = !visible">
                            <svg-icon iconName="tree-table" class-name="select" />
                        </div>
                    </template>
                </el-popover>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs, nextTick, onMounted } from 'vue'
import { ElTree } from 'element-plus'
// import { Search } from '@element-plus/icons-vue'
import { Session } from '@/utils/storage'
import commonV from '@/common/index'
import api from '@/api'

//列表
const props = defineProps({
    //搜索列表
    searchList: {
        type: Array,
        default: () => {
            return []
        }
    },
    //配置项
    allConfigList: {
        type: Array,
        default: () => {
            return []
        }
    },
    //用户喜好
    userPreferences: {
        type: String,
        default: ''
    }
})

const emits = defineEmits(['conditionalQuery', 'modifyPreference'])

onMounted(() => {
    getUserPreferences()
})

//数据
let searchBox = ref({})
//tree节点 
let tree = ref(null)

//配置项开关
let visible = ref(false)

let state = reactive({
    loading: false,
    checked: true,
    defaultSelect: [], //选中项
    userhabit_id: 0, //用户喜好id
    configList: [],
    defaultProps: {
        id: "prop",
        label: 'label'
    }
})

//先根据用户喜好获取用户常展示字段
let getUserPreferences = async () => {
    if (props.userPreferences) {
        state.loading = true
        let params = {
            user_id: Session.get('UserMsg').id,
            type: props.userPreferences
        }
        let res = await api.getaxiosdata("userhabit", params)
        if (res && res.length) {
            state.userhabit_id = res[0].id
            tree.value.setCheckedKeys(JSON.parse(res[0].page_content))
            orderHandle(JSON.parse(res[0].page_content))
            state.defaultSelect = JSON.parse(res[0].page_content)
            emits('modifyPreference', JSON.parse(res[0].page_content))
            state.loading = false
            return
        }
        orderHandle([])
        changechecked()
        let keys = []
        configList.value.forEach(it => keys.push(it.prop))
        state.defaultSelect = keys
        emits('modifyPreference', [])
        state.loading = false
        return
    }
}

//处理排序好的数据
let orderHandle = (sortArr) => {
    //将tree节点中有需要禁用的禁用
    let arr = JSON.parse(JSON.stringify(props.allConfigList))
    arr.forEach(it => {
        if (['linkTo'].includes(it.columType)) {
            it.disabled = true
        }
    })
    let startOrder = []
    sortArr.forEach(it => {
        arr.forEach(i => {
            if (i.prop == it) {
                startOrder.push(i)
            }
        })
    })
    let endOrder = arr.filter(it => !sortArr.includes(it.prop))
    state.configList = [...startOrder, ...endOrder]
}

let { loading, checked, defaultProps, configList } = toRefs(state)

//全选
let changechecked = () => {
    nextTick(() => {
        if (state.checked) { // 全选
            tree.value.setCheckedNodes(props.allConfigList)
        } else {
            // 取消选中
            //如果是点击的链接 就不能操作
            let notLink = props.allConfigList.filter(it => ['linkTo'].includes(it.columType))
            tree.value.setCheckedNodes(notLink)
        }
    })
}

//拖动
let allowDrop = (draggingNode, dropNode, type) => {
    //链接不可拖动
    if (draggingNode.data.columType == 'linkTo') {
        return false
    }
    //不能拖到链接前面
    if (dropNode.data.columType == 'linkTo' && type === "prev") {
        return false
    }

    if (draggingNode.level === dropNode.level) {
        if (draggingNode.parent.id === dropNode.parent.id) {
            // 向上拖拽 || 向下拖拽
            return type === "prev" || type === "next"
        }
    }

    // 不同级进行处理
    return false
}

//排序
let sort = () => {
    // 拖拽之后会改变选中，再次默认选中
    // 确保数据渲染到tree之后再做checked
    nextTick(() => {
        tree.value.setCheckedKeys(state.defaultSelect)
    })
}

//单选 
let check = (data, checkNodes) => {
    state.defaultSelect = checkNodes.checkedKeys
}

//配置项改变
let checkChange = () => { }

//保存
let savesetting = async () => {
    state.loading = true
    let params = {
        user_id: Session.get('UserMsg').id,
        type: props.userPreferences,
        page_content: JSON.stringify(tree.value.getCheckedKeys())
    }
    let method = "post"
    if (state.userhabit_id) {
        params.id = state.userhabit_id
        method = "patch"
    }
    let res = await api.changeaxiosdata("userhabit", method, params)
    if (res) {
        emits('modifyPreference', JSON.parse(res.page_content))
    }
    state.loading = false
}

//重置
let resetsetting = () => {
    //默认全部
    tree.value.setCheckedNodes(props.allConfigList)
    nextTick(() => {
        savesetting()
    })
}

//搜索按钮
let conditionalQuery = () => {
    emits('conditionalQuery', searchBox.value)
}

//给搜索初始值
let setSearchData = (searchVal) => {
    searchBox.value = searchVal
}

defineExpose({ setSearchData })

</script>

<style lang="scss" scoped>
.search-box {
    width: 100%;
    padding: 10px 15px;
    background-color: rgb(245, 247, 251);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .search-params {
        width: 90%;
        display: flex;
        flex-wrap: wrap;

        .search-it {
            margin: 5px 15px 5px 0;
        }
    }
}

.submit {
    display: flex;
    align-items: center;

    .el-button {
        margin-right: 8px;
    }

    .btn-config {
        padding: 4px 5px;
        background-color: #d5d1d1;
        border-radius: 3px;
        cursor: pointer;
        color: #fff;

        &:hover {
            box-shadow: 0 2px 12px #0000001a;
        }
    }
}
</style>